package com.whsxt.dao;

import com.whsxt.common.Constant;
import com.whsxt.common.PageInfo;
import com.whsxt.pojo.User;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author 武汉尚学堂
 */
public class UserDao  extends BaseDao{

    /**
     * 根据用户名和密码查询用户
     * @param username
     * @param password
     * @return
     */
    public User  selectUserByNameAndPassword(String username,String password){
        String sql = "select id,username,password,realname,role,deleted,img from user where username = ? and password = ?";
        User user = super.selectOne(sql, User.class, username, password);
        return  user;
    }

    public PageInfo<User> selectPage(Map<String, String> params, String page, String limit) {
        String sql = "select id,username,password,realname,role,deleted,create_time as createTime,deleted_time as deletedTime from user where 1=1 ";
        if (params.containsKey("realname")){
            sql = sql + " and realname like '%"+params.get("realname")+"%' ";
        }
        if (params.containsKey("role")){
            sql = sql + " and role ="+params.get("role");
        }
        if (params.containsKey("deleted")){
            sql = sql + " and deleted ="+params.get("deleted");
        }
        PageInfo<User> userPage = super.selectPage(sql,User.class,page,limit);
        return userPage;
    }

    public User selectUserByName(String username) {
        String sql = "select id from user where username = ?";
        User user = super.selectOne(sql, User.class, username);
        return  user;
    }

    public void insert(String username, String password, String realname, String role) {
        String sql = "insert into user(username,password,realname,role) value(?,?,?,?)";
        super.executeUpdate(sql,username,password,realname,role);
    }

    public void updatePassword(String id, String password) {
        String sql = "update user set password = ? where id = ?";
        super.executeUpdate(sql,password,id);
    }


    public void delete(String id, Integer invalid) {
        String sql = "update user set deleted = ?,deleted_time = ? where id = ?";
        super.executeUpdate(sql,invalid,new Date(),id);
    }

    public List<User> selectAllSalesman() {
        String sql = "select id,realname from user where role = ? and deleted = ?";
        return  super.selectList(sql,User.class, Constant.USER_ROLE_SALARY,Constant.VALID);
    }

    public void updateImg(Integer id, String url) {
        String sql = "update user set img = ? where id = ?";
        super.executeUpdate(sql,url,id);
    }
}
